package cn.xuexiluxian.open.admin.controller.system;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.xuexiluxian.open.common.annotation.Log;
import cn.xuexiluxian.open.common.annotation.RepeatSubmit;
import cn.xuexiluxian.open.common.enums.BusinessType;
import cn.xuexiluxian.open.system.model.entity.SystemUserPost;
import cn.xuexiluxian.open.system.service.ISystemUserPostService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.xuexiluxian.open.common.enums.ResultStatusCodeEnum;
import cn.xuexiluxian.open.common.response.ResponseResult;
import cn.xuexiluxian.open.common.utils.SecurityUtil;
import cn.xuexiluxian.open.system.model.dto.SystemPostDTO;
import cn.xuexiluxian.open.system.model.entity.SystemPost;
import cn.xuexiluxian.open.system.model.req.SystemPostREQ;
import cn.xuexiluxian.open.system.service.ISystemPostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 岗位管理
 */
@Slf4j
@RestController
@RequestMapping("system/post")
public class SystemPostController {
    @Autowired
    private ISystemPostService systemPostService;
    @Autowired
    private ISystemUserPostService systemUserPostService;

    /**
     * 分页查询岗位
     * @param page
     * @param params
     * @return
     */
    @GetMapping(value = "page")
    @Log(title = "岗位管理", businessType = BusinessType.SELECT)
    @PreAuthorize("@permission.hasPermission('system:post:page')")
    public ResponseResult page(Page page, SystemPostREQ params) {
        Page<SystemPost> pageList = systemPostService.pageList(page, params);
        return ResponseResult.ok(pageList);
    }

    /**
     * 删除岗位
     * @param id
     * @return
     */
    @RepeatSubmit
    @GetMapping("delete/{id}")
    @Log(title = "岗位管理", businessType = BusinessType.DELETE)
    @PreAuthorize("@permission.hasPermission('system:post:delete')")
    public ResponseResult delete(@PathVariable String id){
        if(StrUtil.isBlank(id)){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        QueryWrapper<SystemUserPost> queryWrapper = new QueryWrapper<SystemUserPost>();
        queryWrapper.eq("post_id", id);
        List<SystemUserPost> list = systemUserPostService.list(queryWrapper);
        if(list != null && list.size() > 0){
            return ResponseResult.error(ResultStatusCodeEnum.DATA_HAS_RESOURCES);
        }

        boolean b = systemPostService.removeById(id);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    /**
     * 岗位详情
     * @param id
     * @return
     */
    @GetMapping("get/{id}")
    @Log(title = "岗位管理", businessType = BusinessType.SELECT)
    @PreAuthorize("@permission.hasPermission('system:post:get')")
    public ResponseResult get(@PathVariable String id){
        if(StrUtil.isBlank(id)){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        SystemPost systemPost = systemPostService.getById(id);
        if(systemPost != null){
            return ResponseResult.ok(systemPost);
        }
        return ResponseResult.error(ResultStatusCodeEnum.DATA_NO_EXIST);
    }

    /**
     * 添加岗位
     * @param systemPostDTO
     * @return
     */
    @RepeatSubmit
    @PostMapping("add")
    @Log(title = "岗位管理", businessType = BusinessType.INSERT)
    @PreAuthorize("@permission.hasPermission('system:post:add')")
    public ResponseResult add(@RequestBody SystemPostDTO systemPostDTO){
        String userId = SecurityUtil.getUserId();
        String unitId = SecurityUtil.getUnitId();

        SystemPost systemPost = new SystemPost();
        BeanUtils.copyProperties(systemPostDTO, systemPost);
        systemPost.setId(IdUtil.getSnowflakeNextIdStr());
        systemPost.setUnitId(unitId);
        systemPost.setCreateBy(userId);
        systemPost.setCreateTime(new Date());

        boolean b = systemPostService.save(systemPost);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    /**
     * 修改岗位
     * @param systemPostDTO
     * @return
     */
    @RepeatSubmit
    @PostMapping("update")
    @Log(title = "岗位管理", businessType = BusinessType.UPDATE)
    @PreAuthorize("@permission.hasPermission('system:post:update')")
    public ResponseResult update(@RequestBody SystemPostDTO systemPostDTO){
        String userId = SecurityUtil.getUserId();
        if(systemPostDTO == null || StrUtil.isBlank(systemPostDTO.getId())){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        SystemPost systemPost = new SystemPost();
        BeanUtils.copyProperties(systemPostDTO, systemPost);
        systemPost.setUpdateBy(userId);
        systemPost.setUpdateTime(new Date());

        boolean b = systemPostService.updateById(systemPost);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    /**
     * 全部岗位
     * @return
     */
    @GetMapping("all")
    @Log(title = "岗位管理", businessType = BusinessType.SELECT)
    @PreAuthorize("@permission.hasPermission('system:post:page')")
    public ResponseResult all(){
        QueryWrapper<SystemPost> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("enabled", 1);
        queryWrapper.orderByAsc("sort");
        queryWrapper.orderByDesc("create_time");
        List<SystemPost> list = systemPostService.list(queryWrapper);
        return ResponseResult.ok(list);
    }
}